package com.healthy.healthyserver.Controller;

import com.healthy.healthyserver.Controller.Converter.WxMappingJackson2HttpMessageConverter;
import com.healthy.healthyserver.Controller.Message.Code2session;
import com.healthy.healthyserver.Controller.Request.LoginCode;
import com.healthy.healthyserver.Entity.User;
import com.healthy.healthyserver.repository.UserRepository;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping(value="/login")
public class LoginController {

    @Value("${healthy-app.wechat.appid}")
    private String appid;

    @Value("${healthy-app.wechat.secret}")
    private String secret;

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value="/code", method= RequestMethod.POST)
    public User login(@RequestBody LoginCode body) {


        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + this.appid
                + "&secret=" + this.secret
                + "&js_code=" + body.getCode() + "&grant_type=authorization_code";

        Code2session json = restTemplate.getForObject(url, Code2session.class);

        User user = new User();
        if (json.getErrcode() == null || json.getErrcode() == 0) {
            // 查找是否已经存在该用户
            List<User> users = userRepository.findByWechatOpenId(json.getOpenid());
            if (users.size() > 0) {
                return users.get(0);
            } else {
                // 创建新用户
                user.setWechatOpenId(json.getOpenid());
                userRepository.save(user);
                return user;
            }
        } else {
            user.setId(0L);
            return user;
        }
    }
}
